<template>
    <div>
        <div id="main" style="width: 800px;height:600px;" ref="echarts">

        </div>
    </div>
</template>
<script>
import * as d3 from "d3";
import * as tf from '@tensorflow/tfjs'
export default {
    data() {
        return {
            x: tf.tensor2d([[],]),
            y: tf.tensor2d([[],]),
            w: tf.variable(tf.tensor([[]])),
            trfficData: {
                "sex": [],
                "age": [],
                "monthMoney": [],
                "personNum": [],
                "trfficTool": []
            },
            markLineOpt: {
                animation: false,
                label: {
                    formatter: 'y = x ',
                    align: 'right'
                },
                lineStyle: {
                    type: 'solid'
                },
                tooltip: {
                    formatter: 'y = 0.5 '
                },
                data: [
                    [
                        {
                            coord: [0, 0.5],
                            symbol: 'none'
                        },
                        {
                            coord: [150, 0.5],
                            symbol: 'none'
                        }
                    ]
                ]
            }
            ,
            option: {
                title: {
                    text: "出行多变量逻辑回归",
                    left: 'center',
                    top: 0
                },
                grid: [
                    { left: '7%', top: '7%', width: '80%', height: '80%' },
                ],
                tooltip: {
                    formatter: 'Group {a}: ({c})'
                },
                xAxis: [
                    { gridIndex: 0, min: 0, max: 150 },
                ],
                yAxis: [
                    { gridIndex: 0, min: 0, max: 1 },
                ],
                series: [
                    {
                        name: 'I',
                        type: 'scatter',
                        xAxisIndex: 0,
                        yAxisIndex: 0,
                        data: [],
                        markLine: {},
                        itemStyle:{
                            color: ''
                        }
                    },
                ]
            }
        }
    },
    methods: {
        echartSet: async function () {
            var myCharts = this.$echarts.init(this.$refs.echarts);
            await this.dataSet()
            await this.LogConstruct()
            var yArray = await this.w.matMul(this.x).exp().pow(-1).add(1).pow(-1).dataSync();
            var realyY= await this.y.dataSync();
            var w=await this.w.dataSync();
            var data = [];
            var colors=["#5470c6","#91cc75","#ea7ccc"]
            var colorArray=new Array();
            for (var i = 0; i < yArray.length; i++) {
                colorArray.push(colors[realyY[i]])
                data.push([i, yArray[i]]);
            }
            this.option.series[0].data=data;
            var str="y=";
            for(var i=0;i<w.length;i++){
                str+=`${w[i].toFixed(2)}(x${i})`
            }
            this.option.series[0].itemStyle.color=(e)=>{
                return colorArray[e.dataIndex]
            };
            this.markLineOpt.label.formatter=str;
            this.option.series[0].markLine=this.markLineOpt;
            myCharts.setOption(this.option);
        },
        predict(x) {
            /* 
              y = [[w0,w1,w2]]*[
                              [125,29],
                              [256,8000],
                              [6000,32000]
                            ]
            */
           /*
                    1/(1+e^z)
           */
            return tf.tidy(() => {
                return this.w.matMul(x).exp().pow(-1).add(1).pow(-1);
                
            });
        },
        LogConstruct() {
           this.train(this.x,this.y,300)
        }, train(x, y, numIterations) {

            const learningRate = 0.03;  //学习率
            const optimizer = tf.train.adam(learningRate);

            for (let iter = 0; iter < numIterations; iter++) {
                optimizer.minimize(() => {
                    const predsYs = this.predict(x);
                    return tf.losses.logLoss(y, predsYs);
                });
            }
        },
        dataSet: async function () {
            var { datax, datay, trfficData, dataxCount } = await this.getData();
            this.trfficData = trfficData;
            this.x = tf.tensor(datax)
            this.y = tf.tensor(datay)
            this.w = tf.variable(tf.tensor([new Array(dataxCount - 1).fill(0.0001)]))
            this.train(this.x, this.y, this.k);
            this.$emit("data", trfficData);
        },
        getData: async function () {
            var datax = [];
            var datay = [];
            var trfficData = {
                "sex": [],
                "age": [],
                "monthMoney": [],
                "personNum": [],
                "trfficTool": []
            }
            await d3.csv("./出行/逻辑回归.csv", function (data, error) {
                for (var name in data) {
                    if(data[name]=="男") data[name]=1;
                    else if(data[name]=="女") data[name]=0;
                    else if(data[name]=="私家车") data[name]=1;
                    else if(data[name]=="自行车") data[name]=0;
                    else if(data[name]=="公交地铁") data[name]=1;
                    trfficData[name].push(data[name]);
                }
            })
            var dataxCount = 0;
            for (var name in trfficData) {
                dataxCount++;
                if (name != "trfficTool") datax.push(trfficData[name])
                else datay.push(trfficData[name])
            }
            return { trfficData, datax, datay, dataxCount };
        }
    },
    mounted: async function () {
        this.echartSet();
    }
}
</script>
<style lang="less" scoped></style>